<template>
  <div>
    <Row>
      <Col :span="16">
        <Form inline :model="queryForm" :label-width="90">
          <FormItem label="一级分类：" style="width: 220px;">
            <Select v-model="queryForm.firstCode" @on-change="firstChange" clearable>
              <Option v-for="item in firstList" :value="item.code" :key="item.code">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="二级分类：" style="width: 220px;">
            <Select v-model="queryForm.secondCode" @on-change="secondChange" clearable>
              <Option v-for="item in secondList" :value="item.code" :key="item.code">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="三级分类：" style="width: 220px;">
            <Select v-model="queryForm.thirdCode" @on-change="thirdChange" clearable>
              <Option v-for="item in thirdList" :value="item.code" :key="item.code">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="课程名称：" style="width: 300px;">
            <Select v-model="queryForm.courseId" @on-change="courseChange('query')" clearable>
              <Option v-for="item in courseList" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="适用等级：" style="width: 300px;">
            <Select v-model="queryForm.level" @on-change="levelChange('query')" clearable>
              <Option v-for="item in levelList" :value="item" :key="item">level{{item}}</Option>
            </Select>
          </FormItem>
          <FormItem label="课时：" style="width: 300px;">
            <Select v-model="queryForm.hour" clearable>
              <Option v-for="item in hourList" :value="item.hour" :key="item.hour">{{item.hour}}</Option>
            </Select>
          </FormItem>
          <FormItem label="教材类型：" style="width: 300px;">
            <Select v-model="queryForm.type">
              <Option v-for="item in materialTypeList" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="教材名称：" style="width: 300px;">
            <Input v-model="queryForm.name" placeholder="请输入教材名称"/>
          </FormItem>
        </Form>
      </Col>
      <Col :span="8">
        <Button type="primary" @click="search" v-hasPermission="'search'" style="margin-right: 10px;">查询</Button>
        <Button type="primary" @click="openAdd" v-hasPermission="'masterialAdd'" style="margin-right: 10px;">添加教材</Button>
        <Button type="primary" @click="openAddBatch" v-hasPermission="'materialBatchAdd'">添加课程素材包</Button>
      </Col>
    </Row>
    <Card>
      <Table :columns="columns" :data="materialList"></Table>
      <Page :total="total" show-total show-sizer @on-change="changePage" @on-page-size-change="changePageSize"
            :page-size="queryForm.pageSize"
            :page-index="queryForm.pageIndex" style="margin-top: 10px"/>
    </Card>
    <Modal title="教材基本信息" v-model="addMaterialModal" width="800">
      <Form :model="addData" :rules="addRules" ref="addData" :label-width="100">
        <FormItem prop="name" label="教材名称：" style="width: 80%;">
          <Input type="textarea" v-model="addData.name" placeholder="可输入最多60个中文字符以内的商品名称"/>
        </FormItem>
        <FormItem prop="firstCode" label="课程分类：" style="width: 80%;">
          <Row>
            <Col span="8">
              <Select v-model="addData.firstCode" @on-change="firstChange" placeholder="选择一级分类" clearable style="width: 95%">
                <Option v-for="item in firstList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
            <Col span="8">
              <Select v-model="addData.secondCode" @on-change="secondChange" placeholder="选择二级分类" clearable style="width: 95%">
                <Option v-for="item in secondList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
            <Col span="8">
              <Select v-model="addData.thirdCode" @on-change="thirdChange" placeholder="选择三级分类" clearable style="width: 95%">
                <Option v-for="item in thirdList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem prop="courseId" label="课程名称：" style="width: 80%;">
          <Select v-model="addData.courseId" @on-change="courseChange('add')" clearable placeholder="选择课程">
            <Option v-for="item in courseList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem prop="level" label="适用等级：" style="width: 80%;">
          <Select v-model="addData.level" @on-change="levelChange('add')" clearable placeholder="选择等级">
            <Option v-for="item in levelList" :value="item" :key="item">level{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem prop="hour" label="适用课时：" style="width: 80%;">
          <Select v-model="addData.hour" clearable placeholder="选择课时">
            <Option v-for="item in hourList" :value="item.hour" :key="item.hour">{{item.hour}}</Option>
          </Select>
        </FormItem>
        <FormItem prop="type" label="教材类型：" style="width: 80%;">
          <RadioGroup v-model="addData.type">
            <Radio v-for="item in materialTypeList" :label="item.id" :key="item.id">{{item.name}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="上传资料：">
          <input type="file" @change="handleFileChange"><Button type="primary" @click="lookMaterial(addData)" v-if="addData.fileName">查看</Button>
        </FormItem>

        <FormItem label="课程资料详情：">
          <EditorBar v-model="addData.template" :isClear="isClear"></EditorBar>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button type="primary" @click="addMaterial" :loading="loadAddBtn">确定</Button>
      </div>
    </Modal>
    <Modal title="教材信息" v-model="showMasterial" width="800">
      <div style="width: 100%;height: auto" v-if="typeMasterial===1">
        <div v-html="materialUrl">
          <div>{{materialUrl}}</div>
        </div>
      </div>
      <div style="width: 100%;height: 500px" v-else>
        <iframe
          :src="materialUrl"
          frameBorder="0"
          height="100%"
          width="100%"
        />
      </div>
    </Modal>
    <Modal title="添加课程素材包" v-model="addMaterialBatchModal" width="800">
      <Form :model="addBatchData" :rules="addBatchRules" ref="addBatchData" :label-width="100">
        <FormItem prop="name" label="素材名称：" style="width: 80%;">
          <Input type="textarea" v-model="addBatchData.name" placeholder="可输入最多60个中文字符以内的商品名称"/>
        </FormItem>
        <FormItem prop="firstCode" label="课程分类：" style="width: 80%;">
          <Row>
            <Col span="8">
              <Select v-model="addBatchData.firstCode" @on-change="firstChange" placeholder="选择一级分类" clearable style="width: 95%">
                <Option v-for="item in firstList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
            <Col span="8">
              <Select v-model="addBatchData.secondCode" @on-change="secondChange" placeholder="选择二级分类" clearable style="width: 95%">
                <Option v-for="item in secondList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
            <Col span="8">
              <Select v-model="addBatchData.thirdCode" @on-change="thirdChange" placeholder="选择三级分类" clearable style="width: 95%">
                <Option v-for="item in thirdList" :value="item.code" :key="item.code">{{item.name}}</Option>
              </Select>
            </Col>
          </Row>
        </FormItem>
        <FormItem prop="courseId" label="课程名称：" style="width: 80%;">
          <Select v-model="addBatchData.courseId" @on-change="courseChange('add')" clearable placeholder="选择课程">
            <Option v-for="item in courseList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="素材文件：" required>
          <input type="file" @change="handleBatchFileChange">
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancelBatch">取消</Button>
        <Button type="primary" @click="addMaterialBatch" :loading="loadAddBtn">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import http from '@/libs/http';
  import EditorBar from '@/components/WangEditor'
  export default {
    components: {
      EditorBar
    },
    data() {
      const validateFile = (rule, file, cb) => {
        if (!file) {
          cb(new Error('请添加文件'))
        } else {
          cb()
        }
      }
      return {
        materialTypeList:[
          {id:1,name:'课程教材'},
          {id:2,name:'原声诵读'},
          {id:3,name:'素材下载'},
          {id:4,name:'录播视频'},
        ],//教材类型列表 1-课程教材/预习资料,2-原声诵读,3-素材下载,4-录播视频
        isClear: false,
        columns: [
          {title: '教材编码', key: 'code', algin: 'center'},
          {title: '教材名称', key: 'name', algin: 'center'},
          {title: '课程名称', key: 'courseName', algin: 'center'},
          {
            title: '适用等级', key: 'level', algin: 'center', render: (h, params) => {
              return h('div', {}, "Level " + params.row.level)
            }
          },
          {
            title: '课时', key: 'hour', algin: 'center', render: (h, params) => {
              return h('div', {}, "Lesson " + params.row.hour)
            }
          },
          {
            title: '教材类型', key: 'type', algin: 'center', render: (h, params) => {
              return h('div', params.row.type === 1 ? '课程教材' : params.row.type === 2 ? '原声诵读' : params.row.type === 3 ? '素材下载' : params.row.type === 4 ? '录播视频' : '其他')
            }
          },
          {title: '二级分类', key: 'secondName', algin: 'center'},
          {title: '三级分类', key: 'thirdName', algin: 'center'},
          {title: '上传时间', key: 'createTime', algin: 'center'},
          {
            title: '管理', key: 'actions', algin: 'center',width: 150, render: (h, params) => {
              return h('div', [
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px',
                  marginBottom: '3px',
                  // display: params.row.status === 1 ? 'inline-block' : 'none'
                },
                on: {
                  click: () => {
                    this.masterialAudit(params.row)
                  }
                },
                directives: [
                  {name: 'hasPermission', value: "masterialAudit"}
                ]
              }, '删除'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    // disabled: params.row.status === 1 ? false : true
                  },
                  style: {
                    marginRight: '5px',
                    marginBottom: '3px',
                    // display: params.row.status === 1 ? 'inline-block' : 'none'
                  },
                  on: {
                    click: () => {
                      this.editMaterial(params.row)
                    }
                  },
                  directives: [
                    {name: 'hasPermission', value: "masterialEdit"}
                  ]
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    // disabled: params.row.status === 1 ? false : true
                  },
                  style: {
                    marginRight: '5px',
                    marginBottom: '3px',
                    // display: params.row.status === 1 ? 'inline-block' : 'none'
                  },
                  on: {
                    click: () => {
                      this.lookMaterial(params.row)
                    }
                  },
                  directives: [
                    {name: 'hasPermission', value: "masterialDetail"}
                  ]
                }, '查看')
              ])
            }
          },
        ],
        materialList: [],
        total: 0,
        addMaterialModal: false,
        thirdId: null,
        hour: null,
        loadAddBtn: false,
        addData: {},
        addRules: {
          firstCode: [
            {required: true, message: '一级分类不能为空', trigger: 'change'}
          ],
          secondCode: [
            {required: true, message: '二级分类不能为空', trigger: 'change'}
          ],
          thirdCode: [
            {required: true, message: '三级分类不能为空', trigger: 'change'}
          ],
          name: [
            {required: true, message: '教材名称不能为空', trigger: 'blur'},
            {type: 'string', max: 60, message: '字数限制在60以内', trigger: 'blur'}
          ],
          courseId: [
            {required: true, type: 'number', message: '请选择课程名称', trigger: 'change'}
          ],
          level: [
            {required: true, type: 'number', message: '适用等级不能为空', trigger: 'change'}
          ],
          type: [
            {required: true, type: 'number', message: '教材类型不能为空', trigger: 'change'}
          ],
          hour: [
            {required: true, type: 'number', message: '课时不能为空', trigger: 'change'}
          ],
          // file: [
          //   {required: false, type: 'object', message: '请添加文件', trigger: 'change'},
          //   // { validator: validateFile, trigger: 'change' }
          // ]
        },
        addBatchRules: {
          firstCode: [
            {required: true, message: '一级分类不能为空', trigger: 'change'}
          ],
          secondCode: [
            {required: true, message: '二级分类不能为空', trigger: 'change'}
          ],
          thirdCode: [
            {required: true, message: '三级分类不能为空', trigger: 'change'}
          ],
          name: [
            {required: true, message: '教材名称不能为空', trigger: 'blur'},
            {type: 'string', max: 60, message: '字数限制在60以内', trigger: 'blur'}
          ],
          courseId: [
            {required: true, type: 'number', message: '请选择课程名称', trigger: 'change'}
          ],
          // file: [
          //   {required: false, type: 'object', message: '请添加文件', trigger: 'change'},
          //   // { validator: validateFile, trigger: 'change' }
          // ]
        },
        fileReload: false,
        firstList: [],
        secondList: [],
        thirdList: [],
        courseList: [],
        levelList: [],
        hourList: [],
        queryForm: {
          firstCode: null,
          secondCode: null,
          thirdCode: null,
          courseId: null,
          level: null,
          hour: null,
          name: null,
          pageIndex: 1, pageSize: 10
        },
        materialUrl: null,
        showMasterial:false,
        typeMasterial:null,
        materialsActionUrl: null,
        addOrEdit: null,
        addMaterialBatchModal: false,
        addBatchData: {}
      }
    },
    methods: {
      openAddBatch() {
        this.addMaterialBatchModal = true
        this.addBatchData = {}
        this.$refs['addBatchData'].resetFields()
        this.getFirstList()
      },
      addMaterialBatch() {
        this.$refs['addBatchData'].validate(valid => {

          if (valid) {
            this.loadAddBtn = true;
            const formData = new FormData()
            for (let k in this.addBatchData) {
              k !== 'id' && formData.append(k, this.addBatchData[k])
            }
            http._postwithupload({
              vm: this,
              url: '/manager/materials/materialBatchUpload',
              data: formData,
              success: res => {
                const msg = '添加成功！'
                this.$Message.success(msg)
                this.$refs['addBatchData'].resetFields();
                this.addMaterialBatchModal = false
                this.loadAddBtn = false;
                this.addBatchData = {}
                this.getMaterialList()
              },
              error: res => {
                this.loadAddBtn = false;
              }
            })
          }
        })
      },
      cancelBatch() {
        this.addBatchData = {}
        this.addMaterialBatchModal = false
        this.$refs['addBatchData'].resetFields()
      },
      lookMaterial: function (row, cb) {
        http.get({
          vm: this,
          url: '/manager/materials/lookMaterial',
          data: {materialId: row.id},
          success: res => {
            console.log(res);
            this.materialUrl = res.data;
            this.showMasterial = true;
            this.typeMasterial = row.type
            cb && cb()
          }
        })
      },
      openAdd() {
        this.addMaterialModal = true
        this.addOrEdit = true
        this.materialsActionUrl = '/manager/materials/add'
        this.fileReload = false
        setTimeout(() => {
          this.fileReload = true
        }, 0);
        this.addData = {}
        this.$refs['addData'].resetFields()
        this.getFirstList()
      },
      addMaterial() {
        this.$refs['addData'].validate(valid => {

          if (valid) {
            this.loadAddBtn = true;
            const formData = new FormData()
            for (let k in this.addData) {
              k !== 'id' && formData.append(k, this.addData[k])
            }
            if(!this.addOrEdit){
              formData.append('id', this.addData.id)
            }
            http._postwithupload({
              vm: this,
              url: this.materialsActionUrl,
              data: formData,
              success: res => {
                const msg = this.addOrEdit ? '添加成功！' : '编辑成功！'
                this.$Message.success(msg)
                this.$refs['addData'].resetFields();
                this.addMaterialModal = false
                this.loadAddBtn = false;
                this.addData = {}
                this.getMaterialList()
              },
              error: res => {
                this.loadAddBtn = false;
              }
            })
          }
        })
      },
      cancel() {
        this.addData = {}
        this.addMaterialModal = false
        this.$refs['addData'].resetFields()
      },
      editMaterial({
          //    id, question, answer, type, time, firstId, secondId, thirdId, courseId, level,hour, options:
          // _options,
          code, courseId, courseName, createTime, file, fileName, firstId, firstName, hour, id, level, name, secondId, secondName, template, thirdId, thirdName, type, updateTime
           }) {
        this.$refs['addData'].resetFields()
        this.addMaterialModal = true
        this.addOrEdit = false
        this.materialsActionUrl = '/manager/materials/edit';
        this.getFirstList(() => {
          const _firstCode = this.firstList.find(f => f.id === firstId)
          const firstCode = _firstCode && _firstCode.code || '';
          this.addData = Object.assign({}, this.addData = { courseId, id, name, type, code, courseName, createTime, file, fileName, template, firstCode , firstId, firstName, updateTime })
          this.getSecondList(firstCode,() => {
            const _secondCode = this.secondList.find(s => s.id === secondId)
            const secondCode = _secondCode && _secondCode.code || ''
            this.addData = Object.assign({}, this.addData, {secondCode, secondId, secondName})
            this.getThirdList(secondCode,() => {
              const _thirdCode = this.thirdList.find(t => t.id === thirdId)
              const thirdCode = _thirdCode && _thirdCode.code || ''
              this.addData = Object.assign({}, this.addData, {thirdCode, thirdId, thirdName})
              this.getCourseList(() => {
                const course = this.courseList.find(c => c.id === courseId);
                if (course) {
                  this.addData = Object.assign({}, this.addData, {courseId: course.id});
                  this.getLevelList(courseId,() => {
                    const level_ = this.levelList.find(l => l === level);
                    if (level_) {
                      this.addData = Object.assign({}, this.addData, {level: level_});
                      this.getHourList(courseId,level_,() => {
                        const levelHour = this.hourList.find(l => l.hour === hour);
                        if (levelHour) {
                          this.addData = Object.assign({}, this.addData, {hour: levelHour.hour});
                        }
                      })
                    }
                  })
                }
              })
            })
          })
        })
        // this.isSelect = type === 1 ? true : false
        // this.addData = { code, courseId, courseName, createTime, fileName, firstId, firstName, hour, id, level, name, secondId, secondName, template, thirdId, thirdName, type, updateTime }
      },
      search() {
        this.getMaterialList(() => {
          this.$Message.success('查询成功！')
        })
      },
      getMaterialList(cb) {
        http.get({
          vm: this,
          url: '/manager/materials/list',
          data: this.queryForm,
          success: res => {
            this.materialList = res.data.list
            this.total = res.data.total
            cb && cb()
          }
        })
      },
      firstChange(val) {
        this.addData.secondCode = null
        this.addData.thirdCode = null
        this.addData.id = null
        this.addData.courseId = null
        this.addData.level = null
        this.addData.hour = null
        if (val) {
          const _firstId = this.firstList.find(f => f.code === val)
          this.addData.firstId = _firstId && _firstId.id || null
          this.getSecondList(val)
        } else {
          this.secondList = []
          this.thirdList = []
          this.courseList = []
          this.levelList = []
          this.hourList = []
        }
      },
      secondChange(val) {
        this.addData.thirdCode = null
        this.addData.id = null
        this.addData.courseId = null
        this.addData.level = null
        this.addData.hour = null
        if (val) {
          const _secondId = this.secondList.find(s => s.code === val)
          this.addData.secondId = _secondId && _secondId.id || null
          this.getThirdList(val)
        } else {
          this.thirdList = []
          this.courseList = []
          this.levelList = []
          this.hourList = []
        }
      },
      thirdChange(val) {
        this.addData.id = null
        this.addData.courseId = null
        this.addData.level = null
        this.addData.hour = null
        if (val) {
          const _thirdId = this.thirdList.find(item => item.code === val)
          this.addData.thirdId = _thirdId && _thirdId.id || null
          this.getCourseList()
        } else {
          this.courseList = []
          this.levelList = []
          this.hourList = []
        }
      },
      courseChange(val) {
        console.log(val);
        if (val === 'query') {
          this.queryForm.level = null
          this.queryForm.hour = null
          this.getLevelList(this.queryForm.courseId)
          this.levelList = []
          this.hourList = []
        } else if (val === 'add') {
          this.addData.level = null
          this.addData.hour = null
          this.getLevelList(this.addData.courseId)
          this.levelList = []
          this.hourList = []
        }
      },
      levelChange(val) {
        if (val === 'query') {
          this.queryForm.hour = null;
          this.getHourList(this.queryForm.courseId, this.queryForm.level)
        } else if (val === 'add') {
          this.addData.hour = null;
          this.getHourList(this.addData.courseId, this.addData.level)
        }
      },

      getFirstList(cb) {
        http.get({
          vm: this,
          url: '/manager/course-classification/getAll',
          data: {type: 1},
          success: res => {
            this.firstList = res.data
            cb && cb()
          }
        })
      },
      getSecondList(code, cb) {
        http.get({
          vm: this,
          url: '/manager/course-classification/getAll',
          data: {type: 2, parentCode: code},
          success: res => {
            this.secondList = res.data
            cb && cb()
          }
        })
      },
      getThirdList(code, cb) {
        http.get({
          vm: this,
          url: '/manager/course-classification/getAll',
          data: {type: 3, parentCode: code},
          success: res => {
            this.thirdList = res.data
            cb && cb()
          }
        })
      },
      getCourseList(cb) {
        http.get({
          vm: this,
          url: '/manager/course/listByThird',
          data: {thirdId: this.addData.thirdId},
          success: res => {
            this.courseList = res.data
            cb && cb()
          }
        })
      },
      getLevelList(courseId,cb) {
        if (courseId) {
          http.get({
            vm: this,
            url: '/manager/course/getLevelsByCourseId',
            data: {courseId: courseId},
            success: res => {
              this.levelList = res.data
              cb && cb()
            }
          })
        }
      },
      getHourList(courseId, level, cb) {
        if (courseId && level) {
          http.get({
            vm: this,
            url: '/manager/course/getHoursByCourseAndLevel',
            data: {courseId: courseId, level: level},
            success: res => {
              let hours = res.data;
              this.hourList = [];
              for (let obj of hours) {
                this.hourList.push({hour: obj.hour})
              }
              cb && cb()
            }
          })
        }
      },
      handleFileChange(e) {
        e.target.files[0] ? (this.addData.file = e.target.files[0]) : (delete this.addData.file)

      },
      handleBatchFileChange(e) {
        e.target.files[0] ? (this.addBatchData.file = e.target.files[0]) : (delete this.addBatchData.file)

      },
      masterialAudit({id}) {
        this.$Modal.confirm({
          title: '操作',
          content: `确认对该教材执行删除操作吗？`,
          loading: true,
          onOk: () => {
            http.post({
              vm: this,
              url: '/manager/materials/delete',
              data: {id},
              success: res => {
                this.$Modal.remove();
                this.$Message.success('删除成功!');
                this.getMaterialList()
              }
            })
          }
        })
      },
      changePage(p) {
        this.queryForm.pageIndex = p;
        this.getMaterialList()
      },
      changePageSize(s) {
        this.queryForm.pageSize = s;
        this.getMaterialList()
      }
    },
    mounted() {
      this.getMaterialList();
      this.getFirstList();
    }
  }
</script>
